﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XYX.Print.Models;
using Dapper;
using XYX.Print.Utils;

namespace XYX.Print.Impl
{
    /// <summary>
    /// 打印时参数配置
    /// </summary>
    public class ScanBarCodeConfigImpl
    {

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="barCode"></param>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public ScanBarCodeConfig QueryFirst(string code)
        {
            using (IDbConnection conn = new SqlConnection(DbConnectionManager.ConnString))
            {
                conn.Open();
                string sql = $"SELECT  TOP 1 *  FROM ScanBarCodeConfig WHERE Code='{code}'";
                IEnumerable<ScanBarCodeConfig> result = conn.Query<ScanBarCodeConfig>(sql);
                if (result == null)
                {
                    return default;
                }
                return result.FirstOrDefault();
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="scanBarCodeConfig"></param>
        /// <returns></returns>
        public bool Insert(List<ScanBarCodeConfig> scanBarCodeConfig, Action callback = null)
        {

            using (IDbConnection conn = new SqlConnection(DbConnectionManager.ConnString))
            {

                conn.Open();
                foreach (ScanBarCodeConfig item in scanBarCodeConfig)
                {
                    conn.Insert(item);
                }
                callback?.Invoke();

            }
            return false;
        }
        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="barCode"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public bool CheckIsExists(string barCode)
        {
            using (IDbConnection conn = new SqlConnection(DbConnectionManager.ConnString))
            {
                conn.Open();
                var count = conn.Query<int?>("SELECT TOP 1 Id  FROM ScanBarCodeConfig  WHERE BarCode =@BarCode",
                                                             new { BarCode = barCode });
                if (count != null && count.Any())
                {
                    if (count.FirstOrDefault() >= 1)
                    {
                        return false ;
                    }
                }

            }
            return false;
        }

    }
}
